package com.hd.trans.files.repository;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.hd.trans.files.bean.Audio;
import com.hd.trans.files.model.FileSortModel;
import com.hd.trans.files.model.MusicItems;
import com.hd.trans.files.sort.MediaSortHelper;
import com.hd.trans.utils.DateFormatUtil;
import com.hd.trans.utils.FileUtils;
import com.hd.trans.utils.FileUtilsKotlin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleOnSubscribe;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * Author: yangtianwen
 * Time: 2021/12/10
 * Des: 音频文件数据类
 */
public class AudioDataRepository {

    /**
     * 获取编辑的音频数据
     */
    public Single<List<Audio>> requestEditAudioData(Context context, FileSortModel.ModeItem sortMode) {
        return Single.create((SingleOnSubscribe<List<Audio>>) emitter ->
                emitter.onSuccess(taskRequestAllAudio(context))
        ).map(audioData -> {
            List<Audio> editAudios = filterAudio(audioData);
            return MediaSortHelper.getInstance().sortAudio(editAudios, sortMode);
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 通过扫描本地文件获取录音数据
     */
    public Single<List<Audio>> requestSoundRecordingData(Context context, FileSortModel.ModeItem sortMode) {
        return Single.create((SingleOnSubscribe<List<Audio>>) emitter -> {
                    ArrayList<String> scanDirectories = new ArrayList<>();
                    scanDirectories.add(FileUtils.getSDFilePath());
                    emitter.onSuccess(
                            new MusicItems(context).loadMusicItems(3, scanDirectories, "")
                    );
                }).map(audio -> MediaSortHelper.getInstance().sortAudio(audio, sortMode))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 通过 ContentProvider 获取本地所有的音频
     */
    public Single<List<Audio>> requestAllAudio(Context context, String folder, String[] suffixs, FileSortModel.ModeItem sortMode) {
        return Single.create((SingleOnSubscribe<List<Audio>>) emitter ->
                        emitter.onSuccess(queryAudioBySuffix(context, folder, suffixs))
                ).map(audio -> MediaSortHelper.getInstance().sortAudio(audio, sortMode))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 查询本地音频数据
     */
    private List<Audio> taskRequestAllAudio(Context context) {
        List<Audio> audioData = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null,
                null,
                null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Audio audio = createAudio(cursor);
                if (audio != null && FileUtils.checkFileExists(audio.getUrl())) {
                    audioData.add(audio);
                }
            }
            cursor.close();
        }
        return audioData;
    }

    /**
     * 按后缀名查询本地文件
     */

    public List<Audio> queryAudioBySuffix(Context context, String folder, String[] suffixs) {
        if (suffixs == null || suffixs.length == 0) {
            return new ArrayList<>();
        }
        // 支持多后缀名查询的参数化条件，中间用" OR "隔开：_data LIKE '%.jpg' OR _data LIKE '%.png'
        StringBuilder suffixBuilder = new StringBuilder();
        for (int i = 0; i < suffixs.length; i++) {
            suffixBuilder.append(MediaStore.Audio.Media.DISPLAY_NAME).append(" LIKE '%").append(suffixs[i]).append("'");
            if (i < suffixs.length - 1) {
                suffixBuilder.append(" OR ");
            }
        }
        String selection = suffixBuilder.toString();
        //且满足路径包含"QQ"的参数条件
        if(!TextUtils.isEmpty(folder)){
            selection = "(" + selection + ") and " + MediaStore.Files.FileColumns.DATA + " like '%"+ folder +"%'";
        }
        List<Audio> audioData = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(
                MediaStore.Files.getContentUri("external"),
                null,
                selection,
                null,
                null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Audio audio = createAudio(cursor);
                if (audio != null && FileUtils.checkFileExists(audio.getUrl())) {
                    audioData.add(audio);
                }
            }
            cursor.close();
        }
        return audioData;
    }

    private Audio createAudio(Cursor cursor) {
        long duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
//                歌曲ID：MediaStore.Audio.Media._ID
        int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
        Uri mediaUri =
                ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
//                歌曲的名称 ：MediaStore.Audio.Media.TITLE
        String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
//                歌曲的专辑名：MediaStore.Audio.Media.ALBUM
        String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
//                歌曲的歌手名： MediaStore.Audio.Media.ARTIST
        String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
//                歌曲文件的全路径 ：MediaStore.Audio.Media.DATA
        String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
//                歌曲文件的名称：MediaStroe.Audio.Media.DISPLAY_NAME
        String display_name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
//                歌曲文件的发行日期：MediaStore.Audio.Media.YEAR
        String year = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR));
//                歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        String time = sdf.format(new Date(Math.round(duration)));
//                歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
        long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
        //获取歌曲修改时间
        File file = new File(url);
        long times = file.lastModified();
        //格式化时间，获取年，月，日
        String[] timeArray = DateFormatUtil.getDateByCalendar(times);
        Audio audio = new Audio(id, tilte, album, artist, url, display_name, year, time,
                size, timeArray, duration, false, times);
        audio.setImageRes(getImageRes(display_name));
        return audio.setUri(mediaUri);
    }

    private int getImageRes(String audioName) {
        return FileUtilsKotlin.getFileIcon(audioName);
    }

    /**
     * 筛选 workSpace 下文件
     *
     * @param sourceAudioDate 原数据
     * @return 筛选后的数据
     */
    private List<Audio> filterAudio(List<Audio> sourceAudioDate) {
        List<Audio> editAudios = new ArrayList<>();
        String workspace = FileUtils.getAudioPath();
        for (Audio audio : sourceAudioDate) {
            if (!TextUtils.isEmpty(audio.getUrl()) && audio.getUrl().startsWith(workspace)) {
                editAudios.add(audio);
            }
        }
        return editAudios;
    }
}
